use std::sync::{Arc, Mutex};
use std::net::TcpStream;
use std::io::{Write, ErrorKind, Read};


pub struct Copier {
    lock: Arc<Mutex<()>>,
}

impl Copier {
    pub fn new() -> Copier {
        Copier {
            lock: Arc::new(Mutex::new(()))
        }
    }


    pub fn cp(&mut self, from: &mut TcpStream, to: &mut TcpStream) {
        let mut buf = [0; 10240];

        loop {
            let guard = self.lock.lock().unwrap();
            match from.read(&mut buf) {
                Ok(0) => {
                    return;
                }
                Ok(bytes_read) => {
                    to.write(&buf[..bytes_read]).expect("");
                    //println!("read:{}", bytes_read);
                    continue;
                }
                Err(ref e) if e.kind() == ErrorKind::Interrupted => continue,
                Err(e) => {}
            }
        }
    }
}